<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="preview"
      :file-list="fileList"
      :limit="1"
      :class="{ disable: fileList.length > 0 }"
      :on-remove="removeFn"
      :on-change="changeFn"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showProcess"
      :percentage="percentNum"
      status="success"
      style="width:148px;margin-top:3px"
      :show-text="false"
    />
    <el-dialog
      title="预览"
      :visible="dialogVisible"
      width="30%"
      @close="dialogVisible = false"
    >
      <el-row type="flex" justify="center">
        <img :src="picUrl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDJTN1UgdJiqhIckeJiqgHbeQu85lBKDp9',
  SecretKey: '5tQlpd9OM3TbS3MO9cojNkqfCSTDfqjM'
})
export default {
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      picUrl: '',
      percentNum: 0,
      showProcess: false
    }
  },
  methods: {
    // 预览
    preview(file) {
      console.log(file)
      this.picUrl = file.url
      this.dialogVisible = true
    },
    // 删除
    removeFn(file, newList) {
      this.fileList = [...newList]
    },
    // 添加
    changeFn(file, newList) {
      this.fileList = [...newList]
    },
    // 上传前校验
    beforeUpload(file) {
      // 判断类型
      const types = ['image/jpeg', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片仅支持jpeg和png')
        return false
      }
      // 判断大小
      const maxsize = 500 * 1024
      if (file.size > maxsize) {
        this.$message.error('上传图片不能超过500kb')
        return false
      }
    },
    upload(params) {
      // 开启进度条
      this.showProcess = true
      cos.putObject({
        // 储存桶名
        Bucket: 'hr-test-1306481116',
        // 地区
        Region: 'ap-guangzhou',
        // 名(加一个时间戳保证其唯一，避免同名被覆盖)
        Key: Date.now() + params.file.name,
        // 标准
        StorageClass: 'STANDARD',
        // 上传内容
        Body: params.file,
        // 上传进度中
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentNum = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          // 访问地址
          this.fileList[0].url = 'http://' + data.Location
          // 上传成功
          this.fileList[0].status = 'success'
        }
        setTimeout(() => {
          // 关闭进度条
          this.showProcess = false
        }, 800)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disable {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
